<template>
  <div class="p-4 home">
    <div class="home_calendar">
      <Calendar v-model:value="value" @select="selectDay" @panelChange="panelChange">
        <template #dateCellRender="{ current: val }">
          <ul class="events">
            <Button type="text" v-if="addFilter(val) && !btnFilter(val)" @click="handleCreate(val)">
              <template #icon><PlusOutlined /></template>
            </Button>
            <Popover
              title="日程安排"
              v-if="btnFilter(val)"
              placement="left"
              :overlayStyle="{
                width: '300px',
                height: 'auto',
              }"
            >
              <template #content>
                <div
                  style="display: flex; justify-content: space-between; flex-direction: column"
                  v-for="item in listFilter(val)"
                  :key="item.id"
                >
                  <div style="display: flex; justify-content: space-between">
                    <p>{{ item.title }}</p>
                    <div>
                      {{ formatDate(item.expireTime) }}
                      <EditOutlined @click="handleEdit(item)" :style="{ 'margin-right': '12px' }" />
                      <Popconfirm
                        title="是否要删除该日程？"
                        ok-text="确定"
                        cancel-text="取消"
                        @confirm="deleteSchedule(item)"
                      >
                        <DeleteOutlined />
                      </Popconfirm>
                    </div>
                  </div>
                  <div>
                    <p>{{ item.description }}</p>
                  </div>
                </div>
                <div>
                  <Button type="primary" @click="handleCreate(val)">添加</Button>
                </div>
              </template>
              <Button type="text" danger>
                <template #icon><SmallDashOutlined /></template>
              </Button>
            </Popover>
          </ul>
        </template>
        <!-- <template #monthCellRender="{ current: value }">
          <div v-if="getMonthData(value)" class="notes-month">
            <section>{{ getMonthData(value) }}</section>
            <span>Backlog number</span>
          </div>
        </template> -->
      </Calendar>
    </div>
    <Drawer @register="registerDrawer" @success="handleSuccess" :type="obj.type" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue';
  import moment from 'moment';
  import { useUserStore } from '/@/store/modules/user';
  import { useDrawer } from '/@/components/Drawer';
  import Drawer from './components/Drawer.vue';
  import {
    scheduleList,
    addschedule,
    editschedule,
    deleteschedule,
  } from '/@/api/backs/schedule/index';
  import { Calendar, Button, Popover, message, Popconfirm } from 'ant-design-vue';
  import {
    SmallDashOutlined,
    PlusOutlined,
    DeleteOutlined,
    EditOutlined,
  } from '@ant-design/icons-vue';
  const [registerDrawer, { openDrawer, closeDrawer }] = useDrawer();
  const userStore = useUserStore();
  const nowDate = ref<Date>();
  const obj = reactive({
    schedules: [],
    query: {
      userId: null,
      startTime: '',
      endTime: '',
    },
    type: 'add',
  });
  const value = ref<Moment>();
  // const getMonthData = (value: Moment) => {
  //   if (value.month() === 10) {
  //     return 1394;
  //   }
  // };
  const formatDate = (val) => {
    return moment(val).format('YYYY-MM-DD hh:mm:ss');
  };
  const getList = async () => {
    obj.schedules = await scheduleList(obj.query);
  };
  const btnFilter = (value) => {
    // console.log(value);
    return obj.schedules.some(
      (item) => item?.scheduleDate == moment(value.format('YYYY-MM-DD')).valueOf(),
    );
  };
  const selectDay = (date) => {
    value.value = date;
    Reflect.set(value, 'addShow', true);
  };
  const panelChange = (val) => {
    obj.query.startTime = val.startOf('month').format('X');
    obj.query.endTime = val.endOf('month').format('X');
    getList();
  };
  const addFilter = (val) => {
    if (value.value) {
      return value.value.date() === val.date() && value.value.day() === val.day();
    } else {
      return false;
    }
  };
  const listFilter = (val) => {
    const arr = obj.schedules.find(
      (item) => item.scheduleDate === moment(val.format('YYYY-MM-DD')).valueOf(),
    );
    return arr?.scheduleList || [];
  };
  const deleteSchedule = async (record) => {
    console.log(record);
    try {
      await deleteschedule({ id: record.id });
      message.success('删除成功！');
      getList();
    } catch (error) {}
  };
  //编辑
  const handleEditSuccess = async (formData) => {
    let params = { ...formData };
    try {
      await editschedule(params);
      closeDrawer();
      getList();
    } catch (error) {}
  };
  //新增
  const handleAddSuccess = async (formData) => {
    let params = { ...formData };
    try {
      await addschedule(params);
      closeDrawer();
      getList();
    } catch (error) {}
  };
  function handleSuccess(formData) {
    switch (obj.type) {
      case 'add':
        handleAddSuccess(formData);
        break;
      case 'edit':
        handleEditSuccess(formData);
        break;
    }
  }
  function handleCreate(record) {
    openDrawer(true, {
      record,
      isUpdate: false,
    });
    obj.type = 'add';
  }

  function handleEdit(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
    obj.type = 'edit';
  }
  onMounted(() => {
    nowDate.value = new Date();
    obj.query.userId = userStore.getUserInfo?.user.id;
    obj.query.startTime = moment().startOf('month').format('X');
    obj.query.endTime = moment().endOf('month').format('X');
    getList();
  });
</script>
<style lang="less">
  .home {
    display: flex;
    justify-content: flex-end;
  }
  .home_calendar {
    background-color: #fff;
    // width: 30%;
    .ant-fullcalendar-date {
      // height: 60px;
    }
  }
</style>
